package net.livingflow.web.resource;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;

import net.livingflow.Constants;
import net.livingflow.model.Flow;
import net.livingflow.model.Pack;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.sun.jersey.api.view.Viewable;

/**
 * @author xueqiang.mi
 * @since 2010-12-22
 */
@Path("/myFlows")
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class MyFlowsResource extends BaseResource {

	private long packId = 0;

	@GET
	@Path("{packId}")
	public Response byPack(@PathParam("packId") long packId) {
		this.packId = packId;
		return Response.ok(new Viewable("index", this)).build();
	}

	public List<Flow> getFlows() {
		if (getUserName() == null) {
			return null;
		}
		if (packId != 0) {
			return flowService.getByPack(packId);
		}
		return flowService.getLattestByUser(getUserName(), Constants.PAGE_SIZE);
	}

	public List<Pack> getPacks() {
		if (getUserName() == null) {
			return null;
		}
		return packService.getByUser(getUserName());
	}

	@POST
	@Path("pack/crt")
	@Consumes("application/x-www-form-urlencoded")
	public Response packCrt(@FormParam("name") String name) {
		Pack p = new Pack();
		p.setName(name);
		p.setOwner(getUserName());
		packService.add(p);

		return Response.ok(new Viewable("index", this)).build();
	}

	@GET
	@Path("pack/del")
	@Produces("text/plain")
	public String packDel(@QueryParam("id") long id) {
		Pack p = packService.get(id);
		if (p.getOwner().equals(getUserName())) {
			packService.del(id);
			return "Package deleted successfully";
		} else {
			return "No permission";
		}
	}
}
